import React, {Fragment} from 'react'
import {FormattedMessage, formatMessage} from '@/utils//locale';

import {Button, Col, Form, Input, List, Modal} from 'antd';
import styles from "../../Device/Manage.less";
import Result from '@/components/Result';
import {updateDevice} from "../../../services/device";
import {REFRESH_DEVICES} from "../../../models/device/const";
import {changeMobile, changePassword, updateUser} from "../../../services/user";
import {connect} from "react-redux";
import {formatPhone} from "../../../utils/utils";
import {getCaptchaSagaAction} from "../../../models/login/actionCreator";
import {getCaptcha} from "../../../services/api";

const FormItem = Form.Item;

const passwordStrength = {
  strong: (
    <font className="strong">
      <FormattedMessage id="app.settings.security.strong" defaultMessage="Strong"/>
    </font>
  ),
  medium: (
    <font className="medium">
      <FormattedMessage id="app.settings.security.medium" defaultMessage="Medium"/>
    </font>
  ),
  weak: (
    <font className="weak">
      <FormattedMessage id="app.settings.security.weak" defaultMessage="Weak"/>
    </font>
  ),
};
const formLayout = {
  labelCol: {span: 7},
  wrapperCol: {span: 13},
};

@connect(({user}) => ({
  currentUser: user.currentUser,
}))
@Form.create()
class SecurityView extends React.Component {
  state = {
    visible: false,
    done: false,
    current: {},
    count: 0,
    type: 'password'
  };

  showEditModal = item => {
    let type = 'password';
    if (typeof item.description === 'string') {
      type = 'mobile'
    }
    this.setState({
      visible: true,
      current: item,
      type,
    });
  };

  getData = () => {
    const {currentUser: {mobile}} = this.props;

    return [
      {
        title: formatMessage({id: 'app.settings.security.password'}, {}),
        description: (
          <Fragment>
            {formatMessage({id: 'app.settings.security.password-description'})}：
            {passwordStrength.weak}
          </Fragment>
        ),
      },
      {
        title: formatMessage({id: 'app.settings.security.phone'}, {}),
        description: `${formatMessage(
          {id: 'app.settings.security.phone-description'},
          {}
        )}：${formatPhone(mobile)}`,
      },
      // {
      //   title: formatMessage({id: 'app.settings.security.question'}, {}),
      //   description: formatMessage({id: 'app.settings.security.question-description'}, {}),
      //   actions: [
      //     <a>
      //       <FormattedMessage id="app.settings.security.set" defaultMessage="Set"/>
      //     </a>,
      //   ],
      // },
      // {
      //   title: formatMessage({id: 'app.settings.security.email'}, {}),
      //   description: `${formatMessage(
      //     {id: 'app.settings.security.email-description'},
      //     {}
      //   )}：ant***sign.com`,
      //   actions: [
      //     <a>
      //       <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify"/>
      //     </a>,
      //   ],
      // },
    ];
  };


  handleDone = () => {
    // setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      done: false,
      visible: false,
    });
  };

  handleCancel = () => {
    // setTimeout(() => this.addBtn.blur(), 0);
    this.setState({
      visible: false,
    });
  };

  handleChangeMobile = async (fieldsValue) => {
    const rsp = await changeMobile(fieldsValue);
    if (rsp.status === 'OK') {
      this.setState({
        done: true,
      });
    } else {
      this.setState({visible: false, done: false})
    }
  };
/**
 * 修改密码，
 * 参数：new_password: "123456"
 old_password: "zhaoqi521"
 问题：用户名，是后端自己获取？？？？、
 */
  handleChangePassword = async (values) => {
    const rsp = await changePassword(values);
    if (rsp.status === 'OK') {
      this.setState({
        done: true,
      });
    } else {
      this.setState({visible: false, done: false})
    }
  };

  handleSubmit = e => {
    e.preventDefault();
    const {type} = this.state;
    const {form} = this.props;
    form.validateFields((err, values) => {
      if (err) return;
      if (type === 'mobile') {
        this.handleChangeMobile(values)
      } else {
        this.handleChangePassword(values)
      }
    });
  };

  onGetCaptcha = async () => {
    const {form, dispatch,} = this.props;
    const mobile = form.getFieldValue('mobile');
    await getCaptcha({mobile}, {action: 'cp'});
    let count = 59;
    this.setState({count});
    this.interval = setInterval(() => {
      count -= 1;
      this.setState({count});
      if (count === 0) {
        clearInterval(this.interval);
      }
    }, 1000);
  };


  render() {
    const {visible, done, current, count} = this.state;

    const getModalContent = () => {
      if (done) {
        return (
          <Result
            type="success"
            title="操作成功"
            // description="一系列的信息描述，很短同样也可以带标点。"
            actions={
              <Button type="primary" onClick={this.handleDone}>
                知道了
              </Button>
            }
            className={styles.formResult}
          />
        );
      }
      if (typeof current.description === 'string') {
        return (
          <Form onSubmit={this.handleSubmit}>
            <FormItem label="手机号" {...formLayout}>
              {getFieldDecorator('mobile', {
                rules: [{required: true, message: '请输入新手机号'}],
              })(<Input placeholder="请输入新手机号"/>)}
              <Button
                size="large"
                disabled={count}
                className={styles.getCaptcha}
                onClick={this.onGetCaptcha}
              >
                {count
                  ? `${count} s`
                  : formatMessage({id: 'app.register.get-verification-code'})}
              </Button>
            </FormItem>
            <FormItem label="验证码" {...formLayout}>
              {getFieldDecorator('code', {
                rules: [
                  {
                    required: true,
                    message: formatMessage({id: 'validation.verification-code.required'}),
                  },
                ],
              })(
                <Input
                  size="large"
                  placeholder={formatMessage({id: 'form.verification-code.placeholder'})}
                />
              )}
            </FormItem>
          </Form>
        )
      }
      return (
        <Form onSubmit={this.handleSubmit}>
          <FormItem label="旧密码" {...formLayout}>
            {getFieldDecorator('old_password', {
              rules: [{required: true, message: '请输入旧密码'}],
            })(<Input placeholder="请输入旧密码" type="password"/>)}
          </FormItem>
          <FormItem label="新密码" {...formLayout}>
            {getFieldDecorator('new_password', {
              rules: [{required: true, message: '请输入新密码'}],
            })(<Input placeholder="请输入新密码" type="password"/>)}
          </FormItem>
        </Form>
      );
    };
    const modalFooter = done
      ? {footer: null, onCancel: this.handleDone}
      : {okText: '确定', onOk: this.handleSubmit, onCancel: this.handleCancel};

    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Fragment>
        <List
          itemLayout="horizontal"
          dataSource={this.getData()}
          renderItem={item => (
            <List.Item actions={[
              <a
                onClick={e => {
                  e.preventDefault();
                  this.showEditModal(item);
                }}>
                <FormattedMessage id="app.settings.security.modify" defaultMessage="Modify"/>
              </a>,
            ]}>
              <List.Item.Meta title={item.title} description={item.description}/>
            </List.Item>
          )}
        />
        <Modal
          title={done ? null : `修改${current.title}`}
          className={styles.standardListForm}
          width={640}
          bodyStyle={done ? {padding: '72px 0'} : {padding: '28px 0 0'}}
          destroyOnClose
          visible={visible}
          {...modalFooter}
        >
          {getModalContent()}
        </Modal>
      </Fragment>
    )
  }
}


export default SecurityView;
